package CustomView;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;

import com.qb.devtest.R;
import android.widget.FrameLayout;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;

import utils.MyUtil;

public class CustomAudioPlayer extends FrameLayout {
    Context ctx;
    private Button button;
    private TextView tvName,tvTime;
    private MediaPlayer mediaPlayer;
    private ProgressBar progressBar;
    private SeekBar seekAudio;
    private Handler handler = new Handler();
    private Runnable updateSeekBarTask;
    private Boolean isPlaying = false;

    public CustomAudioPlayer(Context context) {
        super(context);
        init(context);
    }

    public CustomAudioPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        ctx = context;
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.custom_audio_player, this, true);

        button = findViewById(R.id.btn_play);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer == null) {
                    Toast.makeText(context, "请先选择音频文件", Toast.LENGTH_SHORT).show();
                } else {
                    if (isPlaying) {
                        mediaPlayer.pause();
                        isPlaying = false;
                    } else {
                        mediaPlayer.start();
                        isPlaying = true;
                    }
                    setPlayBtn();
                    invalidate();
                }

            }
        });
        tvName = findViewById(R.id.tv_audio_name);
        tvName.setText("还没加载音频");
        tvTime = findViewById(R.id.tv_audio_time);
        tvTime.setText("--/--");
        progressBar = findViewById(R.id.progressBar);
        seekAudio = findViewById(R.id.seek_audio);
        seekAudio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // 当用户拖动滑块时触发
                if (fromUser && mediaPlayer != null) {
                    int total = mediaPlayer.getDuration();
                    mediaPlayer.seekTo(progress);
                    updateTimeShow(progress,total);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 当用户开始拖动滑块时触发
//                handler.removeCallbacks(updateSeekBarTask);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 当用户停止拖动滑块时触发
//                handler.postDelayed(updateSeekBarTask, 1000);
            }
        });
    }

    private void setPlayBtn() {
        // 更新视图以显示播放状态
        String text = "播放";
        int icon = R.drawable.ic_baseline_play_arrow_24;
        if (isPlaying) {
            text = "暂停";
            icon = R.drawable.ic_baseline_pause_24;
            // 开始计时器更新进度条
            handler.postDelayed(updateSeekBarTask, 1000);
        }
        button.setText(text);
        Drawable drawable = ctx.getResources().getDrawable(icon);
        drawable.setBounds(0, 0, 36,36);
        button.setCompoundDrawables(drawable, null, null, null);
    }

    public void loadAudio(Uri uri) {
        // 初始化MediaPlayer
        mediaPlayer = new MediaPlayer();
        setPlayBtn();
        // 设置音频文件路径或URI
        try {
            mediaPlayer.setDataSource(ctx,uri);
            tvName.setText(MyUtil.getFileNameFromUri(ctx,uri));
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(ctx, "音频加载失败，"+e.getMessage(), Toast.LENGTH_SHORT).show();
        }
        // 准备MediaPlayer
        mediaPlayer.prepareAsync();
        // 设置MediaPlayer的准备状态监听器
        mediaPlayer.setOnPreparedListener(mp -> {
            // 准备好后可以开始播放
            mp.start();
            isPlaying = true;
            setPlayBtn();
        });

        updateSeekBarTask = new Runnable() {
            @Override
            public void run() {
                if (mediaPlayer != null && isPlaying) {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    int total = mediaPlayer.getDuration();
                    seekAudio.setProgress(currentPosition);
                    seekAudio.setMax(total);
                    updateTimeShow(currentPosition,total);

                    if (currentPosition<total) {
                        if (isPlaying) handler.postDelayed(this, 1000); // 每100毫秒更新一次
                    } else {
                        handler.removeCallbacks(this);
                        isPlaying = false;
                        setPlayBtn();
                    }
                }
            }
        };
    }

    private void updateTimeShow(int c,int t) {
        int tm = (int) (t / (1000 * 60));
        int ts = (int) ((t % (1000 * 60)) / 1000);
        int cm = (int) (c / (1000 * 60));
        int cs = (int) ((c % (1000 * 60)) / 1000);
        tvTime.setText(cm+":"+cs+"/"+tm+":"+ts);
    }

    // 其他必要的MediaPlayer控制方法，如停止、释放等
    public void stop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacks(updateSeekBarTask);
    }
}
